#include "tileman.h"

using namespace GoldenAges;

CTileManager::CTileManager(void)
{
	const unsigned maxXSize = 8;
	const unsigned maxYSize = 8;

	m_vvTiles.resize(maxXSize);

	for(unsigned x = 0; x < maxXSize; x++)
	{
		m_vvTiles[x].resize(maxYSize);
	}
}

CTileManager::~CTileManager(void)
{
	while(m_vvTiles.size() > 0)
	{
		while (m_vvTiles.back().size() > 0)
		{
			if (m_vvTiles.back().back())
				delete m_vvTiles.back().back();
			m_vvTiles.back().pop_back();
		}
		m_vvTiles.pop_back();
	}
}

void CTileManager::AddTile(CTile *pTile)
{
	if (static_cast<unsigned>(pTile->GetTilePosX()) < m_vvTiles.size()
     && static_cast<unsigned>(pTile->GetTilePosY()) < m_vvTiles[pTile->GetTilePosX()].size())
		m_vvTiles[ pTile->GetTilePosX() ][ pTile->GetTilePosY() ] = pTile;
}

void CTileManager::Render(SDL_Surface* pDestSurf)
{
	for(unsigned y = 0; y < m_vvTiles.size(); y++)
	{
		for (unsigned x = 0; x < m_vvTiles[y].size(); x++)
        {
			if(m_vvTiles[x][y])
				m_vvTiles[x][y]->Render(pDestSurf);
		}
	}
}

void CTileManager::Think(const int &iElapsedTime)
{
    // empty think (j4p3r)
}

bool CTileManager::LoadData(TiXmlElement *pXMLData)
{
	TiXmlNode* pXMLTile = nullptr;
	CTile* pTile;
	while(pXMLTile = pXMLData->IterateChildren(pXMLTile))
    {
		pTile = new CTile;
		if (!pTile->LoadData(pXMLTile->ToElement()))
			return false;
		AddTile(pTile);
	}

	return true;
}

TiXmlElement CTileManager::SaveData(void)
{
	TiXmlElement pXMLTiles("tiles");

	for (unsigned y = 0; y < m_vvTiles.size(); y++)
	{
		for (unsigned x = 0; x < m_vvTiles[y].size(); x++)
        {
			if (m_vvTiles[x][y])
				pXMLTiles.InsertEndChild(m_vvTiles[x][y]->SaveData());
		}
	}

    return pXMLTiles;
}

CTile* CTileManager::GetTile(const int& iX, const int& iY)
{
	if((iX < 0 || static_cast<unsigned>(iX) > m_vvTiles.size())
        && (iY < 0 || static_cast<unsigned>(iY) > m_vvTiles[0].size()))
        return nullptr;

	return m_vvTiles[iX][iY];
}
